/*
 * Copyright 2013 HVTTGROUP
 * http://hvttgroup.com
 *
 */
package com.hvtt.web.controllerUtils;

import com.hvtt.web.controller.Sys_NguoiDungController;
import com.hvtt.web.models.ServiceApi;
import com.hvtt.web.models.Sys_ngonngu;
import com.hvtt.web.models.Sys_nguoidung;
import com.hvtt.web.utilities.ConstClass;
import com.hvtt.web.utilities.GoogleAuthHelper;
import com.hvtt.web.utilities.SocialAPIWrapper;
import com.hvtt.web.utilities.Utilities;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.text.WordUtils;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.primefaces.context.RequestContext;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

/**
 *
 * @author Nguyễn Hoàng Danh
 */
@ManagedBean
@SessionScoped
public class UtilsController implements Serializable {

    private String msgImage = "/Administrator/images/warning.png";
    private String message = "Unknown message";
    private String addThis = "<!-- AddThis Button BEGIN -->\n"
            + "<div class=\"addthis_toolbox addthis_floating_style addthis_counter_style\" style=\"left:1px;top:130px;background:#F4F4F4;\">\n"
            + "<a class=\"addthis_button_facebook_like\" fb:like:layout=\"box_count\"></a>\n"
            + "<a class=\"addthis_button_tweet\" tw:count=\"vertical\"></a>\n"
            + "<a class=\"addthis_button_google_plusone\" g:plusone:size=\"tall\"></a>\n"
            + "<a class=\"addthis_counter\"></a>\n"
            + "</div>\n"
            + "<script type=\"text/javascript\" src=\"//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5051f0a44eb52573\"></script>\n"
            + "<!-- AddThis Button END -->";

    public String getAddThis() {
        return addThis;
    }

    public void setAddThis(String addThis) {
        this.addThis = addThis;
    }

    public UtilsController() {
    }

    public void unsupportMethod() throws SQLException {
        this.setMessage(Utilities.getLanguages("AdMsg0005"));
        this.setMsgImage("/Administrator/images/alert.png");
        RequestContext.getCurrentInstance().update("msg0001ID");
        RequestContext.getCurrentInstance().execute("PF('msg0001').show()");
    }

    public String getMsgImage() {
        return msgImage;
    }

    public void setMsgImage(String msgImage) {
        this.msgImage = msgImage;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    // <editor-fold defaultstate="collapsed" desc="Public Method Code">  
    public String getLanguages(String key) throws SQLException {
        return Utilities.getLanguages(key);
    }

    public String formatNumber(double number, String format) {
        return Utilities.formatNumber(format, number);
    }

    public void redirect(String url) {
        Utilities.redirect(url);
    }

    public String parseDate(Date date, String format) {
        return Utilities.parseDateTime(date, format);
    }

    public String capitalizeWords(String input) {
        return WordUtils.capitalize(input);
    }

    public String getGetPathUserUploadFile() {
        return Utilities.GetPathUserUploadFile();
    }

    public String getGetURLUserUploadFile() {
        return Utilities.GetURLUserUploadFile();
    }

    public void handleFaceBoolEvent(ComponentSystemEvent event) {

        String code = Utilities.getRequest().getParameter("code");
        SocialAPIWrapper socialAPIWrapper = new SocialAPIWrapper();
        String accessToken = socialAPIWrapper.getAccessToken(code);
        socialAPIWrapper.setAccessToken(accessToken);
        JSONObject obj = (JSONObject) socialAPIWrapper.getUserInfo();
        Sys_NguoiDungController controller = Utilities.getManagedBean(Sys_NguoiDungController.class);

        Sys_nguoidung nd = controller.findUserOpenId(String.valueOf(obj.get("id")), ConstClass.OpenId.FACEBOOK.toString());
        Sys_nguoidung sys_nguoidung = controller.getItem();
        if (nd != null) {
            controller.loginOpenId(nd);
        } else if (nd == null) {
            sys_nguoidung.setMa(String.valueOf(obj.get("id")));
            sys_nguoidung.setHo(String.valueOf(obj.get("first_name")));
            sys_nguoidung.setTen(String.valueOf(obj.get("last_name")));
            sys_nguoidung.setGioiTinh(String.valueOf(String.valueOf(obj.get("gender")).charAt(0)).toUpperCase());
            sys_nguoidung.setEmail(String.valueOf(obj.get("email") == null ? "" : obj.get("email")));
            sys_nguoidung.setOpenIdType(Utilities.getRequest().getParameter("value"));
            Utilities.redirect("/registrationOpenId.html");
        } else {
            sys_nguoidung.resetAttribute();
            Utilities.redirect("/registration.html");
        }
    }

    public List<Sys_ngonngu> getListNgonNgu() throws SQLException {
        return Utilities.getListNgonNgu();
    }

    public String getFullDomain() {
        return Utilities.getFullDomainName();
    }

    public void handleTwitterLinkEvent(ComponentSystemEvent event) {
        String url = SocialAPIWrapper.getTwitterLink();//change
        if (url.isEmpty()) {
            Utilities.redirect("/error.html");
        } else {
            Utilities.redirect(url);
        }
    }

    public void handleGoogleLinkEvent(ComponentSystemEvent event) {
        GoogleAuthHelper googleAuthHelper = new GoogleAuthHelper();
        String url = googleAuthHelper.buildLoginUrl();
        HttpSession httpSession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        httpSession.setAttribute(ConstClass.OpenId.GOOGLE.toString(), googleAuthHelper);
        if (url == null || url.isEmpty()) {
            Utilities.redirect("/error.html");
        } else {
            Utilities.redirect(url);
        }
    }
    private static final String PROTECTED_RESOURCE_URL = "https://api.twitter.com/1.1/account/verify_credentials.json";

    public void handleTwitterLinkCallBackEvent(ComponentSystemEvent event) {
        HttpServletRequest req = Utilities.getRequest();
        HttpSession httpsession = req.getSession(true);
        if(req.getParameter("denied")!=null){
            httpsession.setAttribute("ErorData", "Can not connect to Twitter. Please try again!");
            Utilities.redirect("/error.html");
            return;
        }
        String oauth_verifier = req.getParameter("oauth_verifier");
        String username = req.getParameter("username");
        
        if (oauth_verifier.length() > 0) {
            Verifier verifier = new Verifier(oauth_verifier);

            ServiceApi serviceApi = (ServiceApi) httpsession.getAttribute("oauthService");
            OAuthService service = serviceApi.getoAuthService();
            Token requestToken = (Token) httpsession.getAttribute("oauth.request_token");
            httpsession.setAttribute("username", username);
            Token accessToken = service.getAccessToken(requestToken, verifier);
            OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
            service.signRequest(accessToken, request);
            Response response = request.send();

            JSONObject object = (JSONObject) JSONValue.parse(response.getBody());
            Sys_NguoiDungController controller = Utilities.getManagedBean(Sys_NguoiDungController.class);
            Sys_nguoidung sys_nguoidung = controller.getItem();

            Sys_nguoidung nd = controller.findUserOpenId(String.valueOf(object.get("id")), ConstClass.OpenId.TWITTER.toString());
            if (nd != null) {
                controller.loginOpenId(nd);
            } else {
                sys_nguoidung.setMa(String.valueOf(object.get("id")));
                sys_nguoidung.setHo("");
                sys_nguoidung.setTen(String.valueOf(object.get("name")));
                sys_nguoidung.setGioiTinh("O");
                sys_nguoidung.setEmail("");
                sys_nguoidung.setOpenIdType(ConstClass.OpenId.TWITTER.toString());

                httpsession.removeAttribute("oauthService");
                httpsession.removeAttribute("oauth.request_token");
                Utilities.redirect("/registrationOpenId.html");
            }
        } else {
            httpsession.removeAttribute("oauthService");
            httpsession.removeAttribute("oauth.request_token");
            Utilities.redirect("/registration.html");
        }
    }

    public void handleGoogleLinkCallBackEvent(ComponentSystemEvent event) throws IOException {
        Sys_NguoiDungController controller = Utilities.getManagedBean(Sys_NguoiDungController.class);
        Sys_nguoidung sys_nguoidung = controller.getItem();
        HttpSession httpSession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        if(Utilities.getRequest().getParameter("error")!=null){
            httpSession.setAttribute("ErorData", "Can not connect to Google. Please try again!");
            Utilities.redirect("/error.html");
            return;
        }
        GoogleAuthHelper googleAuthHelper = (GoogleAuthHelper) httpSession.getAttribute(ConstClass.OpenId.GOOGLE.toString());
        JSONObject obj = googleAuthHelper.getUserInfoJson(Utilities.getRequest().getParameter("code"));
        if (obj != null) {
            Sys_nguoidung nd = controller.findUserOpenId(String.valueOf(obj.get("id")), ConstClass.OpenId.GOOGLE.toString());
            if (nd != null) {
                controller.loginOpenId(nd);
            } else {
                sys_nguoidung.setMa(String.valueOf(obj.get("id")));
                sys_nguoidung.setHo(String.valueOf(obj.get("family_name")));
                sys_nguoidung.setTen(String.valueOf(obj.get("given_name")));
                sys_nguoidung.setGioiTinh("O");
                sys_nguoidung.setEmail(String.valueOf(obj.get("email")));
                sys_nguoidung.setOpenIdType(ConstClass.OpenId.GOOGLE.toString());
                httpSession.removeAttribute(ConstClass.OpenId.GOOGLE.toString());
                Utilities.redirect("/registrationOpenId.html");
            }
        } else {
            httpSession.removeAttribute(ConstClass.OpenId.GOOGLE.toString());
            sys_nguoidung.resetAttribute();
            Utilities.redirect("/registration.html");
        }
    }
    // </editor-fold>
}
